package com.atguigu.cloud.config;

import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.Retryer;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * openFeign配置类
 * @author: daiziru
 * @createDate: 2024/3/13 20:30
 */
@Configuration
public class FeignConfig implements RequestInterceptor {

    @Bean
    public Retryer myRetryer() {
//        return Retryer.NEVER_RETRY; //Feign默认配置是不走重试策略的

        //最大请求次数为3(1+2)，初始间隔时间为100ms，重试间最大间隔时间为1s
        return new Retryer.Default(100,1,3);
    }

    /**
     * openFeign日志功能配置，默认不打印日志（NONE级别），级别设置为full后，openFeign调用接口时，打印日志
     */
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }


    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null != attributes) {
            HttpServletRequest request = attributes.getRequest();
            requestTemplate.header("Cookie", request.getHeader("Cookie"));
            requestTemplate.header("X-Request-Id", request.getHeader("X-Request-Id"));
        }
    }
}
